<template>
    <a-drawer
        width="80%"
        :title="title"
        placement="left"
        :visible="modal_show"
        :maskClosable="false"
        :closable="false"
        :bodyStyle="{ padding: '0px' }"
        :maskStyle="{ display: 'none' }"
        :mask="false"
        :zIndex="1005"
        @afterVisibleChange="afterVisibleChange"
        >
        <template #extra>
          <a-tooltip  placement="bottom">
              <template #title>关闭</template>
              <a-button @click="onClose" style="margin: 0 auto;margin-right: 10px;">
                <template #icon>
                    <close-outlined />
                </template>
              </a-button>
            </a-tooltip>
        </template>
            <a-row>
                <a-col :span="24"  style="height: 100%;width: 100%;" >
                    <a-list :grid="{ gutter: 2, column: 2 }" :data-source="points" size="small" bordered  >
                        <template #renderItem="{ item, index }">
                            <a-list-item>
                                <a-row>
                                    <div style="height: 50px;width: 100%;font-size: 12px;">
                                            <div style="text-align: center;"> {{ item.tif_name }}</div>
                                            <div style="text-align: center;"> {{ item?.x }}-{{ item?.y }}</div>
                                        </div>
                                </a-row>
                                <a-row>
                                    <div :id="getID(index)"  class="map-container" style="height: 400px;width: 100%;"></div>
                                </a-row>
                            </a-list-item>
                        </template>
                    </a-list>
                </a-col>
            </a-row>
      </a-drawer>
</template>
<script>
export default {
    data() {
        return {
            modal_show: false,
            title:"查看点",
            maps:[],
            players:[],
            point_props:[],//header show
            points:[],
            //mitt
            mitt_match_points_detail_id:"",
            mitt_match_points_detail_back_id:"",
        };
    },
    beforeUnmount() {
        this.$mitt.off('match_points_detail',this.mitt_match_points_detail_id);
    },
    mounted() {
        this.mitt_match_points_detail_id=this.$mitt.on('match_points_detail', async(uid,show_point_details)  => {
            this.mitt_match_points_detail_back_id=uid
            this.modal_show=true
            console.log(show_point_details)
            this.points=show_point_details
            this.title=`查看点(影像数量:${this.points?.length})`
            setTimeout(()=>{
                //清空原有的map
                for (let i = 0; i < this.maps?.length; i++) {
                    let one_map = this.maps[i];
                    one_map.setTarget(null);
                    one_map.dispose();
                }
                this.maps = []
                this.players = []
                this.initmap()
            },500)
        },this?.$?.uid);
        console.log("match_points_detail")
    },
    methods: {
        afterVisibleChange(visible){
            console.log(`visible is ${visible}`)
            if(visible==true){
                this.initmap(); //初始化地图
            }
        },
        getID(target_id){
            return `point-mapcontainer-${target_id}`
        },
        initmap() {
            //add img 
            for (let i = 0; i < this.points?.length; i++) {
                let one_point= this.points[i]
                // in_wkid: 3857
                // out_wkid: 3857
                // point_name: "1861"
                // tif: "D:/2000/XSD-10_PMS_20211123_00216404_0004_L0_MSS_RC_B2.tif"
                // tif_name: "XSD-10_PMS_20211123_00216404_0004_L0_MSS_RC_B2"
                // x: 1428.745605
                // y: -2974.428955
                let projection = `EPSG:${one_point?.out_wkid}`
                let center=[one_point?.x, one_point?.y]
                let one_view = new ol.View({
                    projection:projection ,
                    zoom: 15,
                    center: center,
                    enableRotation: false,
                });
                let url = `${this.$store.state.true_address}/ser/tile?layer=${one_point?.tif}&tilematrix={z}&tilerow={y}&tilecol={x}&in_wkid=${one_point?.in_wkid}&out_wkid=${one_point?.out_wkid}`
                let xyz = new ol.source.XYZ({
                    projection: projection,
                    tileUrlFunction: function ([z, Col, Row], b) {
                        let _url = "";
                        if (this.projectionx == 'EPSG:4326') {
                            _url = this.urlx.replace("{z}", z ).replace("{x}", Col).replace("{y}", Row)
                        }
                        else if (this.projectionx == 'EPSG:3857') {
                            _url = this.urlx.replace("{z}", z).replace("{x}", Col).replace("{y}", Row)
                        }
                        console.log(_url)
                        return _url
                    },
                })
                xyz.urlx = url;
                xyz.projectionx = projection;
                let tile_layer = new ol.layer.Tile({
                    source: xyz,
                    maxZoom: 16,
                })
                let one_map = new ol.Map({
                    controls: [],
                    maxTilesLoading: 18,
                    view: one_view,
                    layers: [],
                    target: this.getID(i),
                });
                one_map.set("index", i)
                tile_layer.set("layertype", "tile")
                one_map.addLayer(tile_layer);
                let ImageLayer = new ol.layer.Image({
                    minZoom: 16,
                    source: this.getImageStatic(),
                    interpolate: false,
                })
                ImageLayer.set("layertype", "static")
                ImageLayer.set("layerfile", one_point?.tif)
                ImageLayer.set("in_wkid", one_point?.in_wkid)
                ImageLayer.set("out_wkid", one_point?.out_wkid)
                one_map.addLayer(ImageLayer);
                let point_source = new ol.source.Vector({
                    features: []
                });
                let point_layer = new ol.layer.Vector({
                    source: point_source,
                    style: this.point_style()
                });
                one_map.addLayer(point_layer);
                this.maps.push(one_map)
                this.players.push(point_layer)
                let feature = new ol.Feature({
                    geometry: new ol.geom.Point(center),
                    properties: {
                        title: one_point.name
                    },
                    style: this.point_style()
                });
                point_source.addFeature(feature)
                tile_layer.getSource().refresh();
                one_map.updateSize();
                let that = this;
                one_map.on("moveend", async ({ frameState, map, target, type }) => {
                    var zoom = map.getView().getZoom();
                    if (this.old_zoom == zoom) {
                        return
                    }
                    var extent = map.getView().calculateExtent();
                    let layers = map.getLayers().getArray();
                    let _tile_layer = layers.find((val) => {
                        return val.get('layertype') == 'tile'
                    })
                    let _static_layer = layers.find((val) => {
                        return val.get('layertype') == 'static'
                    })
                    //判断指定的那个Feature是否存在，若存在就删除并添加新的feature，不存在就直接添加新的feature
                    if (zoom >= 17) {
                        _tile_layer.setVisible(false)
                        _static_layer.setVisible(true)
                        // let layer_in_wkid = _static_layer.get('in_wkid')
                        // let layer_out_wkid = _static_layer.get('out_wkid')
                        console.log(one_point?.tif, JSON.stringify(extent))
                        if (zoom >= 20) { }
                        else {
                            let png_result = await that.$apis.get_static_img(`${this.$store.state.true_address}/ser/statictile?layer=${one_point?.tif}&extent=${JSON.stringify(extent)}&in_wkid=${one_point?.in_wkid}&out_wkid=${one_point?.out_wkid}`)
                            png_result = png_result?.result
                            if (png_result?.img) {
                                let newSource = that.getImageStatic(png_result.extent, png_result.img)
                                _static_layer.setSource(newSource)
                                newSource.refresh()
                            }
                        }
                    }
                    else {
                        _tile_layer.setVisible(true)
                        _static_layer.setVisible(false)
                    }
                    this.old_zoom = zoom - 0
                    console.log((zoom - 0).toFixed(1))
                })
            } 
        },
        getImageStatic(imageExtent=[], url="") {
            return new ol.source.ImageStatic({
                imageExtent: imageExtent,
                interpolate:false,
                url: url,  
            })
        },
        point_style() {
            return new ol.style.Style({
                image:new  ol.style.Icon({
                    // window.btoa()方法用于创建一个 base-64 编码的字符串
                    src: `data:image/svg+xml;base64,` + window.btoa(`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" focusable="false" class="" data-icon="plus" width="20px" height="20px" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896" style="color: #d61446;"><defs><style></style></defs><path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path><path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path></svg>`),
                    size:[20,20],
                })
                // image: new ol.style.Circle({
                //     radius: 4 ,//半径
                //     fill: new ol.style.Fill({//填充样式
                //         color: "#ec8b06",
                //     }),
                //     stroke: new ol.style.Stroke({//边界样式
                //         color: '#555555',
                //         width: 1
                //     }),
                // }),
            })
        },
        onClose(){
            this.modal_show=false
            this.points= []
        },
    },
};
</script>